package com.hc.app.frequencycontrol.strategy;

import com.hc.utils.RedisUtils;
import com.hc.app.constant.FrequencyControlConstant;
import com.hc.app.dto.FixWindowDTO;
import com.hc.app.frequencycontrol.AbstractFrequencyControl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * redis实现固定窗口实现限流算法
 */
@Slf4j
@Service
public class FixWindowFrequencyControl extends AbstractFrequencyControl<FixWindowDTO> {

    @Override
    protected boolean reachRateLimit(Map<String, FixWindowDTO> frequencyControlMap) {
        //批量获取redis统计的值
        List<String> frequencyKeys = new ArrayList<>(frequencyControlMap.keySet());
        // 批量获取redis中key的值
        List<Integer> countList = RedisUtils.mget(frequencyKeys, Integer.class);
        for (int i = 0; i < frequencyKeys.size(); i++) {
            String key = frequencyKeys.get(i);
            Integer count = countList.get(i);
            int frequencyControlCount = frequencyControlMap.get(key).getCount();
            if (Objects.nonNull(count) && count >= frequencyControlCount) {
                //频率超过了
                log.warn("frequencyControl limit key:{},count:{}", key, count);
                return true;
            }
        }
        return false;
    }

    @Override
    protected void addFrequencyControlStatisticsCount(Map<String, FixWindowDTO> frequencyControlMap) {
        frequencyControlMap.forEach((k, v) -> RedisUtils.inc(k, v.getTime(), v.getUnit()));
    }

    @Override
    protected String getStrategyName() {
        return FrequencyControlConstant.FIX_WINDOW;
    }
}
